package com.bw.educate.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.educate.common.ResponseResult;
import com.bw.educate.common.auth.UserInfo;
import com.bw.educate.entity.EduWebsitePage;
import com.bw.educate.entity.EduWebsiteTemplate;
import com.bw.educate.req.WebsiteCommon;
import com.bw.educate.service.IEduWebsiteAdService;
import com.bw.educate.service.IEduWebsiteBaseService;
import com.bw.educate.service.IEduWebsitePageService;
import com.bw.educate.service.IEduWebsiteTemplateService;
import com.bw.educate.util.TemplateFreemark;
import com.bw.educate.util.TestImport;
import com.bw.educate.util.UserUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.IOUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-12
 */
@RestController
@RequestMapping("eduPage")
public class EduWebsitePageController {

    @Autowired
    private IEduWebsitePageService eduWebsitePageService;

    @Autowired
    private IEduWebsiteTemplateService eduWebsiteTemplateService;

    @Autowired
    private TestImport testImport;

    @Autowired
    private UserUtil userUtil;

    @Value("${htmlPaths}")
    private String htmlPath;

    @Autowired
    private RestTemplate restTemplate;



    @Autowired
    private IEduWebsiteBaseService websiteBaseService;
    @Autowired
    private IEduWebsiteAdService adService;



    /**
     * @Description:页面列表
     * @Author: 周明丽
     * @Date: 2020/8/15 21:55
     * @param websiteAd:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("list/{currentPage}/{pageSize}")
    public ResponseResult list(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize,@RequestBody WebsiteCommon websiteAd){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(currentPage,pageSize);
            QueryWrapper queryWrapper=new QueryWrapper();
            if(websiteAd.getName()!=null){
                queryWrapper.like("PAGE_NAME","%"+websiteAd.getName()+"%");
            }
            List<EduWebsitePage> list=eduWebsitePageService.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setResult(pageInfo);

        }catch (Exception e){

            result.setSuccess(false);
            result.setMessage("页面列表查询失败"+e.toString());
        }

        return result;

    }


    /**
     * @Description:删除页面
     * @Author: 周明丽
     * @Date: 2020/8/15 21:51
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("deletePage/{id}")
    public ResponseResult deletePage(@PathVariable("id") Long id){

        ResponseResult result=ResponseResult.SUCCESS();

        try {

            eduWebsitePageService.removeById(id);
            result.setMessage("删除成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("页面删除失败"+e.toString());
        }

        return result;
    }


    /**
     * @Description:根据id查询页面
     * @Author: 周明丽
     * @Date: 2020/8/15 21:53
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("findPage/{id}")
    public ResponseResult findPage(@PathVariable("id") Long id){

        ResponseResult result=ResponseResult.SUCCESS();

        try {
            result.setResult(eduWebsitePageService.getById(id));
            result.setMessage("查询成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("页面查询失败"+e.toString());
        }

        return result;
    }


    /**
     * @Description:页面添加
     * @Author: 周明丽
     * @Date: 2020/8/16 10:20
     * @param eduWebsitePage:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("addSave")
    public ResponseResult addSave(@RequestBody EduWebsitePage eduWebsitePage, HttpServletRequest request){

        ResponseResult result=ResponseResult.SUCCESS();
        UserInfo loginUser = userUtil.getLoginUser(request);

        try {
            if(eduWebsitePage.getId()==null){
                eduWebsitePage.setStatus(0);
                eduWebsitePage.setCreateTime(new Date());
                eduWebsitePage.setCreateUser(loginUser.getId());
                eduWebsitePageService.saveOrUpdate(eduWebsitePage);
            }else{
                eduWebsitePage.setUpdateTime(new Date());
                eduWebsitePage.setUpdateUser(loginUser.getId());
                eduWebsitePageService.updateById(eduWebsitePage);
            }
            result.setMessage("保存成功");

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("页面保存失败"+e.toString());
        }

        return result;
    }


    /**
     * @Description:发布页面
     * @Author: 周明丽
     * @Date: 2020/8/18 11:01
     * @param id:
     * @param response:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("publishPage/{id}")
    public ResponseResult publishPage(@PathVariable("id") Long id, HttpServletResponse response) {

        ResponseResult result = ResponseResult.SUCCESS();
        Map map = new HashMap();//定义数据

        try {
            EduWebsitePage eduWebsitePage = eduWebsitePageService.getById(id);

            EduWebsiteTemplate eduWebsiteTemplate = eduWebsiteTemplateService.getById(eduWebsitePage.getTemplateId());

            if(eduWebsiteTemplate.getName().equals("index")){
                List lists = restTemplate.getForObject(eduWebsitePage.getDataUrl(),List.class);
                map.put("indexs", JSON.toJSONString(lists.get(0)));
//            String htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);

            }else if(eduWebsiteTemplate.getName().equals("banner")){
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("templateid",eduWebsiteTemplate.getId());
                List list = adService.list(queryWrapper);
                map.put("pics", JSON.toJSONString(list));
            }else{

                result.setSuccess(false);
                result.setMessage("发布失败");
            }
            InputStream inputStream = testImport.getLiu(eduWebsiteTemplate.getPath());//输入流
            FileOutputStream outputStream = new FileOutputStream(htmlPath + eduWebsitePage.getRelatives()+"\\"+eduWebsiteTemplate.getName() + ".html");//输出流
            IOUtils.copy(inputStream, outputStream);
            String relativePath=htmlPath + eduWebsitePage.getRelatives();
            TemplateFreemark.gethtmlTemplate(map,eduWebsiteTemplate.getName(),relativePath);
            inputStream.close();
            outputStream.close();
            eduWebsitePage.setStatus(1);
            eduWebsitePageService.saveOrUpdate(eduWebsitePage);
            result.setSuccess(true);
            result.setMessage("发布成功");


        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("发布页面失败" + e.toString());
        }

        return result;
    }

}
